﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kooboo.Commerce.Promotions.CouponCode.Models;

namespace Kooboo.Commerce.Promotions.CouponCode.Controllers
{
    public class CouponCodeController : Controller
    {
        //
        // GET: /CouponCode/

        public ActionResult Index(int id)
        {
            int? selectedReduceType = null;
            var rule = Services.Current.Find(id);
            if (rule == null)
            {
                rule = new Promotion_CouponCode
                {
                    DiscountRuleId = id
                };
            }
            else
            {
                selectedReduceType = rule.ReduceType;
            }

            ViewData["ReduceType"] = EnumHelper.ConvertEnumToSelectListItem<ReduceType>(selectedReduceType);
            return View(rule);
        }

        [HttpPost]
        public ActionResult Index(Promotion_CouponCode promotion, string next)
        {
            if (next == "prev")
            {
                return Json(new { Data = this.Url.Action("Edit", "PromotionRule", new { Id = promotion.DiscountRuleId }) });
            }
            else
            {
                if (promotion.DiscountRuleId > 1)
                {
                    if (promotion.ReduceType == (int)ReduceType.ByFee && promotion.ReduceValue <= 0)
                    {
                        return Json(new { Error = "Please enter a valid discount fee" });
                    }

                    if (promotion.ReduceType == (int)ReduceType.ByPercent && (promotion.ReduceValue < 0 || promotion.ReduceValue > 1))
                    {
                        return Json(new { Error = "Please enter a valid discount fee" });
                    }

                    if (String.IsNullOrEmpty(promotion.GouponCode))
                    {
                        return Json(new { Error = "Please enter a coupon code" });
                    }

                    var item = Services.Current.DataContext.Promotion_CouponCodes.Where(d => d.DiscountRuleId == promotion.DiscountRuleId).FirstOrDefault();
                    if (item == null)
                    {
                        item = new Promotion_CouponCode()
                        {
                            DiscountRuleId = promotion.DiscountRuleId
                        };
                        Services.Current.DataContext.Promotion_CouponCodes.InsertOnSubmit(item);
                    }

                    item.GouponCode = promotion.GouponCode;
                    item.ReduceType = promotion.ReduceType;
                    item.ReduceValue = promotion.ReduceValue;

                    Services.Current.DataContext.SubmitChanges();
                }

                return Json(new { Data = this.Url.Action("Index", "PromotionRule") });
            }
        }
    }
}
